package com.member.web.controller.common;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.member.common.annotation.Anonymous;
import com.member.common.core.domain.AjaxResult;
import com.member.common.utils.ObsUtil;
import com.member.common.utils.uuid.IdUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.UUID;

@Log4j2
@RestController
@RequestMapping("/common/obs")
@Anonymous
public class ObsController {
    //依赖注入
    @Resource
    private ObsUtil obsUtil;

    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) {
        try {
            Map<String, String> map = obsUtil.upload(file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", map.get("url"));
            ajax.put("fileName", map.get("originalFilename"));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }

    }


    @Value("${file.server}")
    private String server;


    @PostMapping("/server/upload")
    public AjaxResult serverUpload(MultipartFile file) {
        try {
            // 生成唯一的文件名
            String fileName = IdUtils.simpleUUID()+ "_" + file.getOriginalFilename();
            Path uploadPath = Paths.get(server, fileName);
            // 确保上传目录存在
            Files.createDirectories(uploadPath.getParent());
            // 保存文件
            Files.copy(file.getInputStream(), uploadPath);


            // 获取当前服务器ip
            InetAddress address = InetAddress.getLocalHost();


            log.info("--------当前服务器IP地址{}：" , address.getHostAddress());
            if("192.168.0.86".equals(address.getHostAddress())){
                // 复制文件到远程服务器
                copyFileWithJSch( uploadPath.toString(),  "root", "192.168.0.239", server);
            }else if("192.168.0.239".equals(address.getHostAddress())){
                // 复制文件到远程服务器
                copyFileWithJSch( uploadPath.toString(),  "root", "192.168.0.86", server);

            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", uploadPath.toString());
            ajax.put("fileName", fileName);
            return ajax;
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

    }

    public void copyFileWithJSch(String localFilePath, String remoteUser, String remoteHost, String remotePath) {
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(remoteUser, remoteHost, 22); // 默认端口是 22
            session.setPassword("77fwYE$cgtxZ*8pz"); // 如果有密码认证
            session.setConfig("StrictHostKeyChecking", "no"); // 跳过主机验证
            session.connect();

            ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();

            // 上传文件
            channelSftp.put(localFilePath, remotePath);

            // 关闭连接
            channelSftp.disconnect();
            session.disconnect();

            System.out.println("文件复制成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
